<?php
namespace App\Libs\wechatRedpack;
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('date.timezone','Asia/Shanghai');   // 定义时区
/*
 * wechatRedpack 微信红包类
 *  */
class wechatRedpack{
    // 定义配置项
    private $nonce_str = "";                                    //随机字符串
    private $sign = "";                                         //签名 在send时生成
    private $mch_billno = "";                                   //商户订单号
    private $mch_id = "";                                       //商户号
    private $wxappid = "";                                      //公众账号appid
    private $send_name = "";                                    //商户名称 派发这名称
    private $nick_name = "";                                    //商户名称
    private $re_openid = "";                                    //用户openid
    private $total_amount = 1;                                  //付款金额
    private $total_num = 1;                                     //红包发放总人数
    private $min_value = 1;                                    //最小金额
    private $max_value = 1;                                    //根据接口要求，上述3值必须一致
    private $wishing = "";                                      //红包祝福语
    private $client_ip = "";                                    //ip地址
    private $act_name = "";                                     //活动名称
    private $remark = "";                                       //备注
    private $apikey = "";                                       //pay 的密钥值

    private $amt_type;      //分裂红包参数 在sendgroup 中进行定义，是常量ALL_RAND

    //证书,在构造函数中定义
    private $apiclient_cert;
    private $apiclient_key;

    //分享参数
    private $isShare = false;
    private $share_content = "";
    private $share_url = "";
    private $share_imgurl = "";

    private $wxhb_inited;

    private $api_hb_group = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";//裂变红包
    private $api_hb_single = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";

    private $error = "OK";

    private $appId;
    private $appSecret;
    private $redirect_uri;

    /*
     * @param $array array();
     * key: appId,appSecret,token,mch_id,wxappid,nick_name,send_name,client_ip,apikey,wishing,act_name,remark,amount
     * */
    public function __construct($datas)
    {
        if(!is_array($datas) && count($datas) == 0){
            $result = array(
                'errcode'=> 40035,
                'errmsg'=>'不合法的参数'
            );
            return json_encode($result);
            exit;
        }
        foreach($datas as $k=>$v){
            $this->$k = $v;
        }
        $this->wxhb_inited = false;     //微信红包初始化状态false
        $this->apiclient_cert =base_path()."/cert/apiclient_cert.pem";
        $this->apiclient_key = base_path()."/cert/apiclient_key.pem";
    }

    /*
     * @sendRedpack 发送红包
     * @param $openid 接收红包的用户openid
     * @param $amount 发放金额，>=1元
     * */
    public function sendRedpack($openid, $amount){
        if(empty(trim($openid)) || empty(trim($amount)))
        {
            $result = array(
                        'errcode'=> 40034,
                        'errmsg'=>'参数缺失'
                    );
            return json_encode($result);
            exit;
        }

        // 构造新红包
        $this->_addRedpack($openid, $amount);
        $sendResult = $this->_send();
        return $sendResult;
    }

    /*
     * 构造新红包 addRedpack
     * @param $openid
     * @param $amount   金额
     * */
    public function _addRedpack($openid, $amount)
    {
        if(!is_numeric($amount)){
            $result = array(
                'errcode'=> 40035,
                'errmsg'=>'不合法的参数'
            );
            return json_encode($result);
            exit;
        }

        $this->_gen_nonce_str();        // 构造随机字符串
        $this->_gen_mch_billno();       // 构造订单号
        $this->_setOpenid($openid);
        $this->_setAmount($amount);
        $this->wxhb_inited = true;      // 标记微信红包已经初始化完成可以发送

        //每次new 都要将分享的内容给清空掉，否则会出现残余被引用
        $this->share_content= "";
        $this->share_imgurl = "";
        $this->share_url = "";
    }

    /*
     * 发出红包
     * 构造签名
     * */
    private function _send($url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", $total_number = 1)
    {
        if(!$this->wxhb_inited){
            $result = array(
                'errcode'=> 60001,
                'errmsg'=>'红包未准备好'
            );
            return json_encode($result);
            exit;
        }
        $this->total_num = $total_number;
        $this->_gen_sign();      // 生成签名

        // 构造提交的数据
        $xml = $this->_genXMLParam();
        // 提交xml，curl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $this->apiclient_cert);
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $this->apiclient_key);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            $data = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
            return json_encode($data);
        }else{
            $this->error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }


    /*
     * 设置红包金额*/
    private function _setAmount($amount)
    {
        $this->total_amount = $amount;
        $this->min_value = $amount;
        $this->max_value = $amount;
    }

    /*
     * 设置用户openid
     * */
    private function _setOpenid($openid)
    {
        $this->re_openid = $openid;
    }

    /*
     * sendGroup()
     * 发送裂变红包，参数为裂变数量
     */
    private function sendGroup($num=3){
        $this->amt_type = "ALL_RAND";       //$amt; 固定值。发送裂变红包组文档指定参数，随机
        return $this->send($this->api_hb_group,$num);
    }

    /*
     * redPack::genXMLParam()
     * 生成post的参数xml数据包
     * 注意生成之前各项值要生成，尤其是Sign
     * return $xml
     */
    private function _genXMLParam(){
        $xml = "<xml>
            <sign>".$this->sign."</sign> 
            <mch_billno>".$this->mch_billno."</mch_billno> 
            <mch_id>".$this->mch_id."</mch_id> 
            <wxappid>".$this->wxappid."</wxappid> 
            <nick_name><![CDATA[".$this->nick_name."]]></nick_name> 
            <send_name><![CDATA[".$this->send_name."]]></send_name> 
            <re_openid>".$this->re_openid."</re_openid> 
            <total_amount>".$this->total_amount."</total_amount> 
            <min_value>".$this->min_value."</min_value> 
            <max_value>".$this->max_value."</max_value> 
            <total_num>".$this->total_num."</total_num> 
            <wishing><![CDATA[".$this->wishing."]]></wishing> 
            <client_ip><![CDATA[".$this->client_ip."]]></client_ip> 
            <act_name><![CDATA[".$this->act_name."]]></act_name> 
            <remark><![CDATA[".$this->remark."]]></remark>       
            <nonce_str>".$this->nonce_str."</nonce_str>
            ";

        if($this->share_content) $xml .= "<share_content><![CDATA[".$this->share_content."]]></share_content>";
        if($this->share_imgurl) $xml .= "<share_imgurl><![CDATA[".$this->share_imgurl."]]></share_imgurl>";
        if($this->share_url) $xml .= "<share_url><![CDATA[".$this->share_url."]]></share_url>";
        if($this->amt_type) $xml .= "<amt_type><![CDATA[".$this->amt_type."]]></amt_type>";
        $xml .="</xml>";

        return $xml;
    }

    /*
     * 生成签名
     */
    private function _gen_sign()
    {
        unset($param);
        $param["act_name"] = $this->act_name;               //活动名称
        if($this->total_num == 1){
            $param["client_ip"] = $this->client_ip;
            $param["max_value"] = $this->max_value;
            $param["min_value"] = $this->min_value;
            $param["nick_name"] = $this->nick_name;
        }

        $param["mch_billno"]    = $this->mch_billno;           //商户订单号
        $param['mch_id']        = $this->mch_id;
        $param["nonce_str"]     = $this->nonce_str;
        $param["re_openid"]     = $this->re_openid;
        $param["remark"]        = $this->remark;
        $param["send_name"]     = $this->send_name;
        $param["total_amount"]  = $this->total_amount;
        $param["total_num"]     = $this->total_num;
        $param["wishing"]       = $this->wishing;
        $param["wxappid"]       = $this->wxappid;

        if($this->share_content) $param["share_content"] = $this->share_content;
        if($this->share_imgurl) $param["share_imgurl"] = $this->share_imgurl;
        if($this->share_url) $param["share_url"] = $this->share_url;

        if($this->amt_type) $param["amt_type"] = $this->amt_type;       //裂变需要的参数，可能暂时用不着

        ksort($param);      //按照键名对关联数组进行升序排序

        $sign_raw = "";
        foreach($param as $k=>$v){
            $sign_raw .= $k."=".$v."&";
        }
        $sign_raw .= "key=".$this->apikey;
        $this->sign = strtoupper(md5($sign_raw));                   //strtoupper函数：把字符串转换为大写。
    }


    /*
     * 随机字符串
     */
    private function _gen_nonce_str()
    {
        $this->nonce_str = strtoupper(md5(mt_rand().time()));
    }

    /*
     * 商户订单号每个订单号必须唯一
     * 组成：mch_id+yyyymmdd+10位一天内不能不能重复的数字
     * 接口根据商户订单支持重入，如出现超时可再调用。
     * @return void
     */
    private function _gen_mch_billno()
    {
        //生成一个长度10，的阿拉伯数字随机字符串
        $rnd_num = array('0','1','2','3','4','5','6','7','8','9');
        $rndstr = "";
        while(strlen($rndstr)<10){
            $rndstr .= $rnd_num[array_rand($rnd_num)];
        }
        $this->mch_billno = $this->mch_id.date("Ymd").$rndstr;
    }
    
}